const DEFAULTS = {
  engine: "bing",
  windowWidth: 500,
  windowHeight: 550,
  openInPopup: true,
  modifierKey: "Alt",
  triggerKey: "LeftClick"
};

const ENGINES = {
  baidu: (q, page = 1) => `https://www.baidu.com/s?wd=${encodeURIComponent(q)}&pn=${(page - 1) * 10}`,
  google: (q, page = 1) => `https://www.google.com/search?q=${encodeURIComponent(q)}&start=${(page - 1) * 10}`,
  bing: (q, page = 1) => `https://www.bing.com/search?q=${encodeURIComponent(q)}&first=${(page - 1) * 10 + 1}`
};

function getSettings() {
  return new Promise((resolve) => {
    chrome.storage.sync.get(DEFAULTS, (items) => resolve(items));
  });
}

function addPopupFlag(url) {
  return url + (url.includes("?") ? "&" : "?") + "popup=1";
}

async function openSearchWindow({ text, screenX, screenY }) {
  if (!text || !text.trim()) return;
  const { engine, windowWidth, windowHeight, openInPopup } = await getSettings();
  const url = ENGINES[engine] ? ENGINES[engine](text.trim(), 1) : ENGINES.baidu(text.trim(), 1);
  const urlWithFlag = addPopupFlag(url);

  if (!openInPopup) {
    chrome.tabs.create({ url });
    return;
  }

  const W = windowWidth, H = windowHeight;
  const left = Math.max(0, screenX + 16);
  const top = Math.max(0, screenY - H - 16);

  try {
    await chrome.windows.create({
      url: urlWithFlag,
      type: "popup",
      width: W,
      height: H,
      top,
      left
    });
  } catch (e) {
    chrome.windows.create({ url: urlWithFlag, type: "popup", width: W, height: H });
  }
}

async function openLinkWindow({ url, screenX, screenY }) {
  const { windowWidth, windowHeight, openInPopup } = await getSettings();
  const urlWithFlag = addPopupFlag(url);

  if (!openInPopup) {
    chrome.tabs.create({ url });
    return;
  }

  const W = windowWidth, H = windowHeight;
  const left = Math.max(0, screenX + 16);
  const top = Math.max(0, screenY - H - 16);

  try {
    await chrome.windows.create({
      url: urlWithFlag,
      type: "popup",
      width: W,
      height: H,
      top,
      left
    });
  } catch (e) {
    chrome.windows.create({ url: urlWithFlag, type: "popup", width: W, height: H });
  }
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg) {
    if (msg.type === "OPEN_SEARCH_WINDOW") {
      openSearchWindow({ text: msg.text, screenX: msg.screenX, screenY: msg.screenY });
      sendResponse({ ok: true });
    } else if (msg.type === "OPEN_LINK_IN_POPUP") {
      openLinkWindow({ url: msg.url, screenX: msg.screenX, screenY: msg.screenY });
      sendResponse({ ok: true });
    }
  }
});
